package cn.wolfcode.p2p.base.service.impl;

import cn.wolfcode.p2p.base.domain.LoginInfo;
import cn.wolfcode.p2p.base.domain.UserInfo;
import cn.wolfcode.p2p.base.exception.CustomException;
import cn.wolfcode.p2p.base.mapper.UserInfoMapper;
import cn.wolfcode.p2p.base.service.IUserInfoService;
import cn.wolfcode.p2p.util.BitStatesUtils;
import cn.wolfcode.p2p.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class UserInfoServiceImpl implements IUserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public void init(LoginInfo loginInfo) {
        UserInfo userInfo = new UserInfo();
        userInfo.setId(loginInfo.getId());
        userInfo.setPhoneNumber(loginInfo.getUsername());
        userInfoMapper.insert(userInfo);

    }

    @Override
    public UserInfo getById(Long id) {
        return userInfoMapper.selectByPrimaryKey(id);
    }

    @Override
    public void basicInfoSave(UserInfo userInfo) {
        //参数校验
        Long userId = UserContext.getLoginInfo().getId();

        //保存数据
        UserInfo oriUserInfo = userInfoMapper.selectByPrimaryKey(userId);
        oriUserInfo.setEducationBackground(userInfo.getEducationBackground());
        oriUserInfo.setHouseCondition(userInfo.getHouseCondition());
        oriUserInfo.setIncomeGrade(userInfo.getIncomeGrade());
        oriUserInfo.setKidCount(userInfo.getKidCount());
        oriUserInfo.setMarriage(userInfo.getMarriage());

        //添加位状态
        if (!oriUserInfo.hasBasicInfo()) {
         oriUserInfo.addState(BitStatesUtils.OP_BASIC_INFO);
        }
        update(oriUserInfo);

    }

    @Override
    public void update(UserInfo userInfo) {
        int count = userInfoMapper.updateByPrimaryKey(userInfo);
        if(count==0){
            throw new CustomException("用户信息修改失败[乐观锁异常]");
        }

    }

}
